#!/usr/bin/env python
import argparse
import sys
import socket
import random
import struct

from scapy.all import sendp, send, get_if_list, get_if_hwaddr
from scapy.all import Packet
from scapy.all import Ether, IPv6, UDP, TCP, IP

def get_if():
    ifs=get_if_list()
    iface=None # "h1-eth0"
    for i in get_if_list():
        if "eth0" in i:
            iface=i
            break;
    if not iface:
        print ("Cannot find eth0 interface")
        exit(1)
    return iface

def is_ipv6_address(addr: str) -> bool:
    """Return True if addr looks like an IPv6 address."""
    try:
        socket.inet_pton(socket.AF_INET6, addr)
        return True
    except socket.error:
        return False


def main():

    if len(sys.argv)<3:
        print ('pass 2 arguments: <destination> "<message>"')
        exit(1)
    # 假如输入为：python3 send.py 10.0.1.1 "hello"
    # 则'send.py'为argv[0] '10.0.1.1'为argv[1] "hello"为argv[2]
    addr = sys.argv[1]
    iface = get_if()

    print ("sending on interface %s to %s" % (iface, str(addr)))

    send_type = 'ipv6' if is_ipv6_address(addr) else 'ipv4'
    if send_type == 'ipv4':
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt /IP(dst=addr)
        pkt = pkt /TCP(dport=1234, sport=random.randint(49152,65535)) / sys.argv[2]
    else:
        saddr = sys.argv[3]
        pkt =  Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt /IPv6(src=saddr,dst=addr)
        pkt = pkt /UDP(dport=4321, sport=1234) / sys.argv[2]

    pkt.show2()
    sendp(pkt, iface=iface, verbose=False)

if __name__ == '__main__':
    main()
